package com.snifferx.managedbeans;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseId;

import org.apache.commons.fileupload.FileItem;
import org.jboss.logging.Logger;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.snifferx.domain.UserEntity;
import com.snifferx.services.UserService;
import com.snifferx.util.RandomStringUtils;
import com.snifferx.util.helper.EmailHelper;

@ManagedBean(name = "registerBean")
@SessionScoped

/*@Component
@Scope("session")
@Qualifier("registerBean")*/
public class RegisterBean implements Serializable {

	private static final long serialVersionUID = -7085606329092302635L;

	@ManagedProperty(value = "#{userEntity}")
	//@Autowired
	private UserEntity regUser;
	@ManagedProperty(value = "#{userService}")
	//@Autowired
	private UserService userService;
	private String key;
	private StreamedContent image;
	private byte[] headshot;
	private static Logger log = Logger.getLogger(RegisterBean.class);
	private Date nowTime;

	private String uploadFileName;

	public RegisterBean() {
		super();
	}

	public String doNextStep() {
		log.debug("Debug doNextStep()");
		// 比较 nextStep 和 nextStep.xhtml的区别
		return "nextStep";
	}

	public String doRegister() {
		log.debug("Debug doRegister()");
		// set enable to true , becasue is new user
		// now set setEnabled directly , not will vialate the pincode later
		this.regUser.setEnabled("1");
		this.regUser.setLoginAttempts(new BigDecimal(0));
		this.regUser.setCreationdate(Calendar.getInstance().getTime());
		// added uploaded image set to new user
		this.regUser.setHeadshot(headshot);
		boolean result = userService.createUser(regUser);
		log.debug("createUser finish...");
		// FacesContext.getCurrentInstance().addMessage(null, new
		// FacesMessage("insert into  DB error ."));
		// return "regSuccess";
		if (!result) {
			return null;
		} else {
			// send email here
			String activationCode = "";
			String fromId = "SnifferX.com";
			String recipientId = regUser.getEmail();
			String adminRecipientId = "g-svcemail@singtel.com";
			activationCode = RandomStringUtils.randomNumeric(10);
			try {
				EmailHelper.sendEshopAccountActivationMail(fromId, recipientId, adminRecipientId, activationCode,
						regUser.getFirstName() + regUser.getLastName(), regUser.getUsername(), regUser.getPassword());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "regSuccess";
		}

	}

	// FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("uploadFile")
	// modified action to actionListen
	public void upload(ActionEvent e) {
		FileItem fileItem = (FileItem) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().remove(key);
		if (fileItem != null) {
			try {
				byte[] data = fileItem.get();
				// set into managedBean data
				this.headshot = data;
				ByteArrayInputStream stream = new ByteArrayInputStream(data);
				//this.setImage(new DefaultStreamedContent(stream, "image/jpg", fileItem.getName()));
				this.setImage(new DefaultStreamedContent(stream, "image/jpg"));

				this.uploadFileName = fileItem.getName();
			} catch (Exception ex) {
			}
		}
	}
	
    public String turnOnRegister()
    {
        Map sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        RegisterBean registerBean = (RegisterBean)sessionMap.get("registerBean");
        sessionMap.remove(registerBean);
        sessionMap.put("registerBean", new RegisterBean());
        return "/register";
    }

	@PostConstruct
	private void generateKey() {
		log.debug("Into  @PostConstruct Method()... ");
		key = UUID.randomUUID().toString();
	}

	public UserEntity getRegUser() {
		return regUser;
	}

	public void setRegUser(UserEntity regUser) {
		this.regUser = regUser;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public StreamedContent getImage() {
/*		FacesContext context = FacesContext.getCurrentInstance();
		if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
			// So, we're rendering the view. Return a stub StreamedContent so
			// that it will generate right URL.
			return new DefaultStreamedContent();
		} else {
			if (this.image != null) {
				// bcos the image preview not be cache , so load it again
				// manually
				log.debug("headshot length:" + this.headshot.length);
				// image = null;
				image = new DefaultStreamedContent(new ByteArrayInputStream(this.headshot), "image/png", this.image.getName());

			}
		}*/
		if (this.image != null) {
			log.debug("headshot length:" + this.headshot.length);
			//image = new DefaultStreamedContent(new ByteArrayInputStream(this.headshot), "image/png", this.image.getName());
			image = new DefaultStreamedContent(new ByteArrayInputStream(this.headshot), "image/png");
		}
		return image;
	}

	public void setImage(StreamedContent image) {
		this.image = image;
	}

	public byte[] getHeadshot() {
		return headshot;
	}

	public void setHeadshot(byte[] headshot) {
		this.headshot = headshot;
	}

	public Date getNowTime() {
		// SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.nowTime = Calendar.getInstance().getTime();
		// System.out.println("format output time :" + sdf.format(date));
		// System.out.println("original output time:" + date);
		return nowTime;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

}
